package project.messagestack;

import project.messagestack.utils.Logger;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

public class BatterySaverManager extends BroadcastReceiver {
  private SharedPreferences mPreferences;
  static String oldRefreshTimer;
  
  @Override
  public void onReceive(Context context, Intent intent) {
     mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
     if (!mPreferences.getBoolean("allowToSaveBattery", false)) {
       Logger.logInfo("Cancelling battery save handling");
       return;
     }
     Logger.logInfo("Handling battery saving");
     // handle specific cases
     SharedPreferences.Editor editor = mPreferences.edit();
     if (intent.getAction().equals(Intent.ACTION_BATTERY_LOW)) {
       oldRefreshTimer = mPreferences.getString("sleepTime", "15s");
       editor.remove("sleepTime");
       editor.putString("sleepTime", "15min");
       editor.commit();
     } else if (intent.getAction().equals(Intent.ACTION_BATTERY_OKAY) ||
                intent.getAction().equals(Intent.ACTION_POWER_CONNECTED)) {
       editor.remove("sleepTime");
       editor.putString("sleepTime", oldRefreshTimer);
       editor.commit();
     } else if (intent.getAction().equals(Intent.ACTION_POWER_DISCONNECTED)) {
       /*
       Intent bat = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
       float charged = bat.getIntExtra("level", 0)*100/bat.getIntExtra("scale", 100);
       Logger.logInfo(""+ charged);
       if (charged <= 0.15) {
         oldRefreshTimer = mPreferences.getString("sleepTime", "15s");
         SharedPreferences.Editor editor = mPreferences.edit();
         editor.remove("sleepTime");
         editor.putString("sleepTime", "5min");
         editor.commit();
       }*/
     }
     
  }

}
